import config from './config'

const http = (options) => {
	return new Promise((resolve, reject) => {
		if(options.showLoading){
			uni.showLoading({
				title: options.showTitle || '加载中...',
				mask: true// 默认遮罩出现可以继续操作
			});
		}
		try {
			uni.request({
				url: (options.baseURL || config.baseURL) + options.url,
				method: options.method || 'POST', // 默认为POST请求
				data: options.data, //请求超时在manifest.json配置
				header: {
					'content-type': options.header == 'form' ? 'application/x-www-form-urlencoded' : 'application/json'
				},
				success: (res) => {
					resolve(res.data)
				},
				fail: (err) => {
					reject(err.data);
					uni.showToast({
						title: '请求失败',
						icon: 'none'
					})
				},
				complete: () => {
					if(options.showLoading){
						uni.hideLoading();
					}
				}
			});
		} catch (e) {
			if(options.showLoading){
				uni.hideLoading();
			}
			uni.showToast({
				title: '服务端异常',
				icon: 'none'
			})
		}

	})
}

export default http
